﻿using NetEasyMusic.Lib.Details;
using NetEasyMusic.Lib.Models;

namespace NetEasyMusic.Lib.Data;

public class Artist : DataBasic
{
    public Artist(string cookie) : base(cookie)
    {
    }

    public Artist(string url, bool isUse = false) : base(url, isUse)
    {
    }

    public Artist()
    {
    }

    
    /// <summary>
    /// 从歌手Id获取歌手信息
    /// </summary>
    /// <param name="id">歌手Id</param>
    /// <returns>歌手信息</returns>
    public async Task<ArtistDetailModel> GetArtist(string id)
    {
        var context = await GetFormString($"/artists?id={id}");
        if (context is null) return new ArtistDetailModel();
        var a = context["hotSongs"]!.Select(x => x["id"]?.ToObject<string>()!).ToArray();
        var hot = a[..(a.Length > 12 ? 12 : ^1)].Aggregate("", (current, token) => current + token + ",");
        var model = new ArtistDetailModel
        {
            Name = context["artist"]!["name"]!.ToObject<string>()!,
            BasicDesc = context["artist"]!["briefDesc"]!.ToObject<string>()!,
            PicUrl = context["artist"]!["picUrl"]!.ToObject<string>()!,
            HotSongs = hot[..^1]
        };
        return model;
    }

    /// <summary>
    /// 从歌手Id获取歌手专辑信息
    /// </summary>
    /// <param name="id">歌手Id</param>
    /// <returns>歌手专辑列表</returns>
    public async Task<AlbumModel[]> GetAlbums(string id)
    {
        var context = await GetFormString($"/artist/album?id={id}");
        if (context == null) return [];
        var list = new List<AlbumModel>();

        var al = new Album();
        foreach (var album in context["hotAlbums"]!)
            list.Add(await al.GetAlbum(album["id"]!.ToObject<string>()!));

        return list.ToArray();
    }

    /// <summary>
    /// 获取歌手专辑信息
    /// </summary>
    /// <param name="id">歌手ID</param>
    /// <returns>获取歌手专辑信息</returns>
    public async Task<AlbumModel[]> GetArtistAlbums(string id)
    {
        var context = await GetFormString($"/artist/album?id={id}");
        if (context == null) return [];
        return context["hotAlbums"]!.Select(album => new AlbumModel()
            { PicUrl = album["picUrl"]!.ToObject<string>()!, Name = album["name"]!.ToObject<string>()! }).ToArray();
    }

    
    /// <summary>
    /// 获取相似歌手
    /// </summary>
    /// <param name="id">歌手ID</param>
    /// <returns>相似歌手</returns>
    public async Task<ArtistModel[]> GetSimilar(string id)
    {
        var context = await GetFormString($"/simi/artist?id={id}&cookie={Cookie}");
        if (context == null) return [];

        return context["artists"]!.Select(x => new ArtistModel
        {
            Name = x["name"]!.ToObject<string>()!,
            Id = x["id"]!.ToObject<string>()!,
            PicUrl = x["picUrl"]!.ToObject<string>()!
        }).ToArray();
    }
}